package vip.xiaonuo.core.sms.modular.smsbao;

import lombok.extern.slf4j.Slf4j;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.sms.SmsSender;
import vip.xiaonuo.core.sms.modular.smsbao.exp.SmsBaoSmsException;
import vip.xiaonuo.core.sms.modular.smsbao.prop.SmsBaoSmsProperties;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : zxw
 * @Date 2023/9/11 16:38
 */
@Slf4j
public class SmsBaoSmsSender implements SmsSender {

    private final SmsBaoSmsProperties smsBaoSmsProperties;

    public SmsBaoSmsSender(SmsBaoSmsProperties smsBaoSmsProperties) {
        this.smsBaoSmsProperties = smsBaoSmsProperties;
    }


    @Override
    public void sendSms(String phone, String templateCode, Map<String, Object> params) {

        log.info(">>> 开始发送短信宝短信，手机号是：" + phone + ",模板号是：" + templateCode + ",参数是：" + params);
        //短信宝发送
        String userName = smsBaoSmsProperties.getUsername();   //账号
        String passWord = smsBaoSmsProperties.getPassword();  //密码
        String validateCode = params.get(CommonConstant.CODE).toString(); //验证码
        String areaCode = params.get(CommonConstant.AREA_CODE).toString(); //国家号

        String phoneNum = phone;
        String smsContent = String.format(templateCode, validateCode);
        log.info("模板号：" + smsContent + "");
        String httpUrl = "http://api.smsbao.com/sms";
        //國際
        if (!("".equals(areaCode) || "+86".equals(areaCode))) {
            httpUrl = "http://api.smsbao.com/wsms";
            phoneNum = areaCode + phone;
        }

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(userName).append("&");
        httpArg.append("p=").append(md5(passWord)).append("&");
        httpArg.append("m=").append(encodeUrlString(phoneNum, "UTF-8")).append("&");
        httpArg.append("c=").append(encodeUrlString(smsContent, "UTF-8"));
        String result = request(httpUrl, httpArg.toString());
        //不等于0发送失败
        if (!result.equals("0")){
            throw new SmsBaoSmsException(result,result);
        }

    }


    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }


}
